

class Call():
    def __init__(self, cmd, until="", timeout=5):
        self.start = time.time()
        self.process = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        self.log = ""
        t = threading.Thread(target=self.recv)
        t.daemon = True
        t.start()
        self.read(until=until, timeout=timeout)

    def write(self, cmd):
        self.process.stdin.write(cmd.encode() + b"\n")
        self.process.stdin.flush()

    def read(self, until="", timeout=5 ):
        start = time.time()
        while time.time() - start < timeout:
            if until in self.log:
                logging.info(self.log)
                return True, self.log
            time.sleep(0.1)
        logging.info(self.log)
        return False, self.log

    def run(self, cmd, until="", timeout=5):
        logging.info(cmd)
        self.log = ""
        self.write(cmd)
        return self.read(until, timeout=timeout)

    def recv(self):
        while self.process.poll() is None:
            data = self.process.stdout.read1()
            try:
                self.log += data.decode(encoding="utf-8")
            except UnicodeDecodeError:
                self.log += data.decode(encoding="gb2312", errors='ignore')


    def __del__(self):
        self.process.kill()